package com.example;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {

    private Connection getConnection() throws SQLException {
        return DatabaseUtil.getConnection();
    }

    public void addUser(User user) throws SQLException {
        String sql = "INSERT INTO users(username, name, type, department, status, password) VALUES(?, ?, ?, ?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getName());
            pstmt.setString(3, user.getType());
            pstmt.setString(4, user.getDepartment());
            pstmt.setString(5, user.getStatus());
            pstmt.setString(6, user.getPassword());
            pstmt.executeUpdate();
        }
    }

    public void updateUser(User user) throws SQLException {
        String sql = "UPDATE users SET name = ?, type = ?, department = ?, status = ? WHERE username = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, user.getName());
            pstmt.setString(2, user.getType());
            pstmt.setString(3, user.getDepartment());
            pstmt.setString(4, user.getStatus());
            pstmt.setString(5, user.getUsername());
            pstmt.executeUpdate();
        }
    }

    public void deleteUser(String username) throws SQLException {
        String sql = "DELETE FROM users WHERE username = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.executeUpdate();
        }
    }

    public List<User> getAllUsers() throws SQLException {
        List<User> userList = new ArrayList<>();
        String sql = "SELECT username, name, type, department, status, password FROM users";
        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                User user = new User(
                    rs.getString("username"),
                    rs.getString("name"),
                    rs.getString("type"),
                    rs.getString("department"),
                    rs.getString("status"),
                    rs.getString("password")
                );
                userList.add(user);
            }
        }
        return userList;
    }

    public List<User> searchUsers(String searchText, String userType) throws SQLException {
        List<User> userList = new ArrayList<>();
        StringBuilder sql = new StringBuilder("SELECT username, name, type, department, status, password FROM users WHERE 1=1");
        
        if (userType != null && !userType.equals("全部")) {
            sql.append(" AND type = ?");
        }
        if (searchText != null && !searchText.trim().isEmpty()) {
            sql.append(" AND (username LIKE ? OR name LIKE ? OR department LIKE ?)");
        }
        
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql.toString())) {
            
            int paramIndex = 1;
            if (userType != null && !userType.equals("全部")) {
                pstmt.setString(paramIndex++, userType);
            }
            if (searchText != null && !searchText.trim().isEmpty()) {
                String likeText = "%" + searchText + "%";
                pstmt.setString(paramIndex++, likeText);
                pstmt.setString(paramIndex++, likeText);
                pstmt.setString(paramIndex++, likeText);
            }

            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                User user = new User(
                    rs.getString("username"),
                    rs.getString("name"),
                    rs.getString("type"),
                    rs.getString("department"),
                    rs.getString("status"),
                    rs.getString("password")
                );
                userList.add(user);
            }
        }
        return userList;
    }

    public void updatePassword(String username, String newPassword) throws SQLException {
        String sql = "UPDATE users SET password = ? WHERE username = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            // TODO: 在实际应用中，密码应该进行哈希处理而不是明文存储
            pstmt.setString(1, newPassword);
            pstmt.setString(2, username);
            pstmt.executeUpdate();
        }
    }
    
    public User getUserByUsername(String username) throws SQLException {
        String sql = "SELECT username, name, type, department, status, password FROM users WHERE username = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return new User(
                    rs.getString("username"),
                    rs.getString("name"),
                    rs.getString("type"),
                    rs.getString("department"),
                    rs.getString("status"),
                    rs.getString("password")
                );
            }
        }
        return null;
    }

    public boolean updateUserRole(String username, String newRole) throws SQLException {
        String sql = "UPDATE users SET type = ? WHERE username = ?";
        
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, newRole);
            pstmt.setString(2, username);
            
            return pstmt.executeUpdate() > 0;
        }
    }
} 